package cn.yunhe.action;

import cn.yunhe.utils.BaseAction;
import lombok.Getter;
import lombok.Setter;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class UpLoad extends BaseAction {

    //文件标题
    @Setter
    @Getter
    private String title;
    //文件
    @Setter
    @Getter
    private File upload;
    //文件类型
    @Setter
    @Getter
    private String uploadContentType;
    //文件名
    @Setter
    @Getter
    private String uploadFileName;
    //保存路径
    @Setter
    private String savePath;

    public String getSavePath() {
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }

    private void doUpload(File file,String uploadFilePath){
        try {
            FileOutputStream fos=new FileOutputStream(uploadFilePath);
            FileInputStream fis=new FileInputStream(file);
            byte[] b=new byte[1024];
            int len=0;
            while ((len=fis.read(b))!=-1){
                fos.write(b,0,len);
            }
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String execute() {
        String uploadPath=getSavePath()+"\\"+getUploadFileName();
        doUpload(upload,uploadPath);
        return SUCCESS;
    }
}
